package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import javax.annotation.Resource;
import java.util.Set;

/**
 * AuthenticatingRealm:自定义认证
 * AuthorizingRealm：自定义认证的同时授权；他是子类继承了authenticatingReam
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Resource
    DtsAdminService adminService;

    @Resource
    DtsRoleService roleService;

    @Resource
    DtsPermissionService permissionService;


    /**
     *授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin dtsAdmin= (DtsAdmin) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Integer[] roleIds = dtsAdmin.getRoleIds();
        //Set<String> roles     查询权限 Set<String> perms;
        Set<String> roles=roleService.findByRoleIds(roleIds);
        Set<String> perms=permissionService.findByRoleIds(roleIds);
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    /**
     *AuthenticationToken:认证
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());

        //根据username查询对象
        DtsAdmin dtsAdmin = adminService.selectOne(username);
        if(null==dtsAdmin){
            throw new UnknownAccountException();
        }
        if(!dtsAdmin.getPassword().equalsIgnoreCase(password)){
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(dtsAdmin,password,this.getName());
    }
}
